package com.cy.gameserver.miniServer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by tiankai.qin on 18/3/1.
 */
@Component
public class MiniServer {

    private static final Logger logger = LoggerFactory.getLogger(MiniServer.class);

    private ServerSocket s;

    private Socket socket = null;

    public MiniServer() {
        try {
            s = new ServerSocket(9091, 3);

            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            socket = s.accept();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        new MyWebServerThread(socket).start();
                    }
                }
            }.start();


//            // server将一直等待连接的到来
//            System.out.println("server将一直等待连接的到来");
//            Socket socket = s.accept();
//            // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
//            InputStream inputStream = socket.getInputStream();
//            byte[] bytes = new byte[1024];
//            int len;
//            StringBuilder sb = new StringBuilder();
//            //只有当客户端关闭它的输出流的时候，服务端才能取得结尾的-1
//            while ((len = inputStream.read(bytes)) != -1) {
//                // 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
//                sb.append(new String(bytes, 0, len, "UTF-8"));
//            }
//            System.out.println("get message from client: " + sb);
//
//            OutputStream outputStream = socket.getOutputStream();
//            outputStream.write("Hello Client,I get the message.".getBytes("UTF-8"));
//
//            inputStream.close();
//            outputStream.close();
//            socket.close();
//            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    class MyWebServerThread extends Thread {
        private Socket socket;

        MyWebServerThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStreamReader is = new InputStreamReader(socket.getInputStream());
                char[] bs = new char[2048];
                PrintStream out;
                out = new PrintStream(socket.getOutputStream());
                StringBuilder msg = new StringBuilder();
                // 如果10毫秒还没有数据，则视同没有新的数据了。
                // 因为有Keep-Alive的缘故，浏览器可能不主动断开连接的。
                // 实际应用，会根据协议第一行是GET还是 POST确定。
                socket.setSoTimeout(10);
                //
                // 此处读入请求数据并做相应的处理
                //
                int len = -1;
                try {
                    while ((len = is.read(bs)) != -1) {
                        msg.append(bs, 0, len);
                        msg.append("\n");
                    }
                } catch (Exception ex) {
                    // ex.printStackTrace();
                }
                // 下面是由服务器直接生成的主页内容
                // 1、首先向客户端输出响应头信息
                out.println("HTTP/1.1 200 OK");
                out.println("Content-Type:text/html;charset:UTF-8");
                out.println();
                // 2、输出
                out.println("您发送的请求如下:");
                out.println(msg.toString());
                out.flush();
                out.close();
                is.close();
                System.out.println(msg.toString());
                logger.info(msg.toString());
                // 关闭连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
